Connecting to MySQL via Python

The following example shows how to connect to the MySQL server via python.

Install pymysql

pip install pymysql

Connect to your server

import pymysql


class MysqlConnection(object):
    def __init__(self):
        self.host = 'your host'
        self.port = 'your port'
        self.user = 'your user name'
        self.passwd = 'your user password'
        self.db = 'your connect database name'

    def connect_mysql(self):
        return pymysql.Connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db)

    def operate_database(self):
        # example select mysql version
        connect = self.connect_mysql()
        cursor = connect.cursor()
        cursor.execute("SELECT VERSION()")
        data = cursor.fetchone()
        print('version is :', data[0])
        connect.close()


if __name__ == '__main__':
    MysqlConnection().operate_database()
Copyright © 2021 Cloud Clusters Inc. all right reserved,powered by GitbookRevised on 09/10/2021

results matching ""

    No results matching ""